/**
 * Created by lihao on 2017/2/6.
 */


import _ from 'lodash'
import { filePath, tabelfirstLine, userMailcol, tplPath, dataRange, mailConfig, mailOptions} from './config';
const fs = require('fs');
const path = require('path');
const Promise = require('bluebird');
const BlueBirdQueue = require('bluebird-queue');
const iconv = require('iconv-lite');
const xlsx = require('node-xlsx');
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const log4js = require('log4js');

//日志设置
log4js.configure({
    "appenders": [
        // 下面一行应该是用于跟express配合输出web请求url日志的
        {"type": "console", "category": "console"},
        // 定义一个日志记录器
        {
            "type": "dateFile",                 // 日志文件类型，可以使用日期作为文件名的占位符
            "filename": "./logs/",     // 日志文件名，可以设置相对路径或绝对路径
            "pattern": "yyyyMMddhh-sendMailLog.txt",  // 占位符，紧跟在filename后面
            "absolute": true,                   // filename是否绝对路径
            "alwaysIncludePattern": true,       // 文件名是否始终包含占位符
            "category": "logInfo"               // 记录器名
        } ],
    "levels":{ "logInfo": "DEBUG"}        // 设置记录器的默认显示级别，低于这个级别的日志，不会输出
});
let logger = log4js.getLogger('logInfo');

//读取邮件模板
let mailTpl = _.template(iconv.decode(fs.readFileSync(path.join(process.cwd(),tplPath)), 'UTF-8'));




//main function
let init = ()=>{
    pathXlsx(path.join(process.cwd(),filePath))
        .then(formatData)
        .then(sendMail)
        .then(function(results){
            transport.close();
            logger.info('全部邮件发送完成！');
            logger.info('共发送邮件：',results.length);
            logger.info('发送成功：',_.filter(results,{status:'response'}).length);
            logger.info('发送失败：',_.filter(results,{status:'error'}).length);
        })
        .catch((error)=>{

        });
};


//load xlsx for path
let pathXlsx = (path)=> {
    return Promise.resolve(xlsx.parse(path));
};

//读取对应表格数据
let formatData = (data)=>{
    return Promise.resolve({
        tableName:data[0].name,
        title:data[0].data[0],
        data:_.drop(data[0].data,tabelfirstLine) //_.find(data,{name:tabelName}).data
    })
};

// 按到设置数据范围生成HTML代码
let displayTpl = (data,tableName,title)=>{
    let beginCol = !_.isEmpty(dataRange) && dataRange[0] > 0 ? dataRange[0] - 1 : 0;
    let endCol = !_.isEmpty(dataRange) && dataRange[1] > 0 && (dataRange[1] - dataRange[0]) > 0 ? (dataRange[1] - beginCol) : _.size(data);
    //mailTpl({ data: item })
    return  mailTpl({
        data: _.take(_.drop(data,beginCol),endCol),
        title:_.take(_.drop(title,beginCol),endCol),
        tableName:tableName,
    });
};

//发送邮件
let addMail = (item, tableName, title, toMail)=>{
    return new Promise((resolve,reject)=>{
        let mailOptionsTemp = _.assign(mailOptions,{
            to: toMail, // 收件列表
            subject: "工资发放条", // 标题
            html: displayTpl(item, tableName, title, toMail) // html 内容
        });
        logger.info(toMail,'邮件发送中。。。');
        console.log(displayTpl(item, tableName, title, toMail));
        resolve({status:'error'});
        // transport.sendMail(mailOptionsTemp, function(error, response) {
        //     if (error) {
        //         logger.warn('邮件发送失败！');
        //         resolve({status:'error',error:error});
        //     } else {
        //         logger.info('邮件发送成功！');
        //         resolve({status:'response',response:response});
        //     }
        // });
    });
};

//链接邮件服务器
let connectMailServer = ()=>{
    // 开启一个 SMTP 连接池
    let transport = nodemailer.createTransport(smtpTransport(mailConfig));
    return transport;
};

//发送列表
let sendMail = (data) =>{
    let list  = data.data;
    let queue = new BlueBirdQueue({
        concurrency: 1, // optional, how many items to process at a time
        onComplete:function () {
            logger.info('完成所有任务!');
        }
    });

    _.map(list,function (item) {
        if(!_.isEmpty(item)){
            queue.add(function () {
                return addMail(item,data.tableName,data.title,item[userMailcol-1]);
            });
        }

    });
    return queue.start();
};

let transport = connectMailServer();
init();